package com.jiandian.service.impl;

import com.jiandian.constant.SignPrizeLogConstants;
import com.jiandian.crudparams.qo.SignPrizeLogQo;
import com.jiandian.crudparams.vo.OnlineSignPrizeLogVo;
import com.jiandian.dao.SignPrizeLogMapper;
import com.jiandian.entity.SignPrizeLog;
import com.jiandian.entity.SignUser;
import com.jiandian.exception.SignPrizeException;
import com.jiandian.page.PageInfo;
import com.jiandian.page.WhereMapUtil;
import com.jiandian.service.SignPrizeLogService;
import com.jiandian.service.SignUserService;
import com.jiandian.util.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;

/**
 * 获奖日志
 *
 * @author houqi Fu
 * @date 2018/12/15
 */
@Service
@Transactional
public class SignPrizeLogServiceImpl implements SignPrizeLogService {

    private static final Logger logger = LoggerFactory.getLogger(SignPrizeLogServiceImpl.class);

    @Autowired
    private SignPrizeLogMapper mapper;

    @Autowired
    private SignUserService signUserService;

    @Override
    public SignPrizeLog add(SignPrizeLog record) {
        // 在提交抽奖日志之前，需要判断这个人是否还有抽奖次数
        Integer userId = record.getUserId();
        SignUser signUser = signUserService.findById(userId);
        if (signUser.getPrizeTimes() <= 0) {
            throw new SignPrizeException("您已无抽奖次数");
        }

        // 是否预设中奖
        if(!signUser.getPrePrize().equals(SignPrizeLogConstants.NO_PRE_PRIZE)){
            // 预设中奖已消耗,则将用户下次预设中奖设置为空
            if (record.getPrizeType().equals(signUser.getPrePrize())){
                signUser.setPrePrize(SignPrizeLogConstants.NO_PRE_PRIZE);
            }
        }
        // 如果获得的奖品为补签卡
        if (record.getPrizeType() == SignPrizeLogConstants.TYPE_SUPPLEMENT) {
            if (!checkAllowGetsSupplement(signUser)) {
                // throw new SignPrizeException("您获取的补签卡次数已达到上限");
            }
            signUser.setSupplementCount(signUser.getSupplementCount() + 1);
        }

        initBasicValue(record);

        int result = mapper.insert(record);
        if (result > 0) {
            // 如果抽奖日志写入完成，则扣减此人的抽奖次数。
            signUser.setPrizeTimes(signUser.getPrizeTimes() - 1);
            signUserService.update(signUser);
            return record;
        }
        throw new SignPrizeException("抽奖出错");

    }

    @Override
    public SignPrizeLog update(SignPrizeLog record) {
        Long id = record.getId();
        if (id == null) {
            return null;
        }
        SignPrizeLog dbSignPrizeLog = mapper.selectByPrimaryKey(id);
        if (dbSignPrizeLog == null) {
            return null;
        }
        BeanUtils.copyProperties(record, dbSignPrizeLog);
        // dbSignPrizeLog.setGmtModified(new Timestamp(System.currentTimeMillis()));
        int result = mapper.updateByPrimaryKey(dbSignPrizeLog);
        if (result > 0) {
            return dbSignPrizeLog;
        }
        return null;
    }

    @Override
    public SignPrizeLog findById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<SignPrizeLog> findAll(PageInfo pageInfo) {
        return mapper.selectAll(pageInfo);
    }

    @Override
    public int selectCount(PageInfo pageInfo) {
        return mapper.selectCount(pageInfo);
    }

    @Override
    public int batchInsert(List<SignPrizeLog> list) {
        for (SignPrizeLog bean : list) {
            initBasicValue(bean);
        }
        return mapper.batchInsert(list);
    }

    @Override
    public List<SignPrizeLog> batchQueryByIds(List<Long> ids) {
        return mapper.batchQueryByIds(ids);
    }

    @Override
    public int delete(Long id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public int delete(SignPrizeLog record) {
        return delete(record.getId());
    }

    @Override
    public int batchDeleteById(List<Long> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            return mapper.batchDeleteById(ids);
        }
        return 0;
    }

    private void initBasicValue(SignPrizeLog record) {
        Timestamp now = new Timestamp(System.currentTimeMillis());
        record.setCreateTime(now);
        // record.setConsumeTime(new Timestamp());
        // record.setGmtCreate(now);
        // record.setGmtModified(now);
    }

    @Override
    public PageInfo getPage(SignPrizeLogQo whereEntity, PageInfo pageInfo) {
        pageInfo.setWhereMap(WhereMapUtil.convertBeanToWhereMap(whereEntity));
        pageInfo.setTotalRecord(selectCount(pageInfo));
        pageInfo.queryPageResult(pageInfo);
        pageInfo.setResultObject(findAll(pageInfo));
        return pageInfo;
    }

    @Override
    public boolean checkAllowGetsSupplement(SignUser signUser) {
        int supplementCount = signUser.getSupplementCount();
        int usedSupplementCount = signUser.getUsedSupplementCount();
        return (supplementCount + usedSupplementCount) < SignPrizeLogConstants.MAX_SUPPLEMENT_COUNT;
    }

    @Override
    public void consumeSupplement(int userId, int limit) {
        mapper.consumeSupplement(userId, limit);
    }

    @Override
    public List<OnlineSignPrizeLogVo> selectByMinId(Long minId) {
        return mapper.selectByMinId(minId);
    }


}
